package com.njit.WeStudy.control;

import com.njit.WeStudy.dao.*;
import com.njit.WeStudy.dataobject.*;
import com.njit.WeStudy.util.ReplaceFileContent;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileWriter;
import java.util.Objects;
import java.util.UUID;

/**
 * @author yuruiqiao
 * @date 2020/1/26
 * @description 发帖功能
 */
@RestController
public class InvitationController {

    @Resource
    private InvitationMapper invitationMapper;

    @Resource
    private LikeMapper likeMapper;

    @Resource
    private StarMapper starMapper;

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private StoreyMapper storeyMapper;

    @Resource
    private SupportMapper supportMapper;

    @RequestMapping(path = "/issue")
    public String issue(@RequestParam("title") String title, @RequestParam("imageUrl") String imageUrl,
                        @RequestParam("content") String content, HttpServletRequest request, HttpSession session) {
        int userId = ((User) session.getAttribute("user")).getUserId();

        /*获取tomcat下templates的真实路径*******/
        /*注意!!!!这个路径不能用内置tomcat跑*******/
        String filePath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("/")).getPath() +
                "templates/users/" + userId;
        // 生成新的,唯一的文件名
        String filename = UUID.randomUUID() + ".html";
        // 新建文件
        File filepath = new File(filePath, filename);
        FileWriter fileWriter;
        //获取模板文件并将内容替换
        String templateFilePath = request.getServletContext().getRealPath("upload/template.html");
        String finalContent = ReplaceFileContent.replaceFileContent(templateFilePath, content);
        if (!finalContent.equals("")) {
            // 判断路径是否存在，如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            try {
                fileWriter = new FileWriter(filepath);
                fileWriter.write(finalContent);
                fileWriter.close();
                //这边执行插入操作
                Invitation invitation = new Invitation();
                invitation.setTitle(title);
                invitation.setPreviewImageUrl(imageUrl);
                invitation.setHtmlUrl("users/" + userId + "/" + filename.substring(0, filename.lastIndexOf(".")));
                invitation.setUserId(userId);
                invitationMapper.insert(invitation);
                return "success";
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "false";
    }

    /**
     * @author yuruiqiao
     * @date 2020/1/29
     * @description 用户点赞的方法
     */
    @RequestMapping(path = "/update/invitation/likeStatus")
    public int updateLikeStatus(HttpSession session, @RequestParam("invitationId") int invitationId) {
        int userId;
        int flag = -1;
        try {
            userId = ((User) session.getAttribute("user")).getUserId();
            //先查询有没有这条记录
            Like mySelfLike = likeMapper.queryMyselfLike(invitationId, userId);
            if (mySelfLike == null) {
                Like like = new Like();
                like.setUserId(userId);
                like.setInvitationId(invitationId);
                like.setIsLiked(true);
                likeMapper.insert(like);
                flag = 1;
            } else {
                //如果有记录,查看当前用户对当前帖子的喜欢状态
                boolean myselfIsLike = mySelfLike.getIsLiked();
                if (myselfIsLike) {
                    int i = likeMapper.updateLikeStatusByUserIdAndInvitationId(invitationId, false, userId);
                    if (i == 1) {
                        flag = 0;
                    }
                } else {
                    int i = likeMapper.updateLikeStatusByUserIdAndInvitationId(invitationId, true, userId);
                    if (i == 1) {
                        flag = 1;
                    }
                }
            }
            if (flag == 1) {
                int totalLikeNumber = likeMapper.likeQueryByInvitationId(invitationId).size();
                invitationMapper.updateNumById("like_number", totalLikeNumber, invitationId);
                return 1;//1表示点赞
            } else if (flag == 0) {
                int totalLikeNumber = likeMapper.likeQueryByInvitationId(invitationId).size();
                invitationMapper.updateNumById("like_number", totalLikeNumber, invitationId);
                return flag;//0表示取消
            } else {
                return flag;//-1表示数据库操作有误
            }
        } catch (NullPointerException ne) {
            return -2;//表示要登录
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -3;//未知错误
    }

    /**
     * @author yuruiqiao
     * @date 2020/1/29
     * @description 查询当前帖子点赞的数量
     */
    @RequestMapping(path = "/update/invitation/like")
    public int updateLike(@RequestParam("invitationId") int invitationId) {
        return likeMapper.likeQueryByInvitationId(invitationId).size();
    }

    /**
     * @author yuruiqiao
     * @date 2020/1/29
     * @description 用户收藏帖子(关注用户)的方法
     */
    @RequestMapping(path = "/update/target/starStatus")
    public int updateStarStatus(HttpSession session, @RequestParam("targetId") int targetId, @RequestParam("targetType") String targetType) {
        int userId;
        int flag = -1;
        try {
            userId = ((User) session.getAttribute("user")).getUserId();
            //先查询有没有这条记录
            Star mySelfStar = starMapper.queryMyselfStar(targetId, targetType, userId);
            if (mySelfStar == null) {
                Star star = new Star();
                star.setUserId(userId);
                star.setTargetId(targetId);
                star.setTargetType(targetType);//比之前要多设置一个变量
                star.setIsStared(true);
                starMapper.insert(star);
                flag = 1;
            } else {
                //如果有记录,查看当前用户对当前帖子(其它用户)的收藏(关注)状态
                boolean myselfIsStar = mySelfStar.getIsStared();
                if (myselfIsStar) {
                    int i = starMapper.updateStarStatusByUserIdAndTargetId(targetId, targetType, false, userId);
                    if (i == 1) { flag = 0;}
                } else {
                    int i = starMapper.updateStarStatusByUserIdAndTargetId(targetId, targetType, true, userId);
                    if (i == 1) { flag = 1;}
                }
            }
            if (flag == 1) {
                int totalStarNumber = starMapper.starQueryByTargetId(targetId, targetType).size();
                invitationMapper.updateNumById("star_number", totalStarNumber, targetId);
                return 1;//1表示收藏
            } else if (flag == 0) {
                int totalStarNumber = starMapper.starQueryByTargetId(targetId, targetType).size();
                invitationMapper.updateNumById("star_number", totalStarNumber, targetId);
                return flag;//0表示取消
            } else {
                return flag;//-1表示数据库操作有误
            }
        } catch (NullPointerException ne) {
            return -2;//表示要登录
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -3;//未知错误
    }

    /**
     * @author yuruiqiao
     * @date 2020/1/29
     * @description 查询当前帖子收藏的数量(其它用户被关注的数量)
     */
    @RequestMapping(path = "/update/target/star")
    public int updateStar(@RequestParam("targetId") int targetId, @RequestParam("targetType") String targetType) {
        return starMapper.starQueryByTargetId(targetId, targetType).size();
    }

    /**
     * @author yuruiqiao
     * @date 2020/1/31
     * @description 层主发表帖子
     */
    @RequestMapping(path = "/storey")
    public String storey(HttpSession session, @RequestParam("invitationId") int invitationId,
                         @RequestParam("content") String content) {
        try {
            int userId = ((User) session.getAttribute("user")).getUserId();
            Storey storey = new Storey();
            storey.setUserId(userId);
            storey.setInvitationId(invitationId);
            storey.setContent(content);
            storeyMapper.insert(storey);
            //要将invitation的comment数量更新一下,暂时只有跟帖数量,之后会加所有层主下的所有回复
            int totalStoreyNumber = storeyMapper.storeyQueryByInvitationId(invitationId).size();
            int totalCommentNumber = commentMapper.commentQueryByInvitationId(invitationId).size();
            invitationMapper.updateNumById("comment_number", totalStoreyNumber+totalCommentNumber, invitationId);
            return "success";
        } catch (NullPointerException ne) {
            return "needLogin";//用户要登录
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }

    /**
     * @author yuruiqiao
     * @date 2020/1/31
     * @description 回复层主及以下方法
     */
    @RequestMapping(path = "/comment")
    public String comment(HttpSession session, @RequestParam("targetUserId") int targetUserId, @RequestParam("content") String content,
                          @RequestParam("invitationId") int invitationId, @RequestParam("storeyId") int storeyId,@RequestParam("targetType")String targetType) {
        try {
            int userId = ((User) session.getAttribute("user")).getUserId();
            Comment comment = new Comment();
            comment.setUserId(userId);
            comment.setInvitationId(invitationId);
            comment.setStoreyId(storeyId);
            comment.setTargetUserId(targetUserId);
            comment.setTargetType(targetType);
            comment.setContent(content);
            commentMapper.insert(comment);
            //要将invitation的comment数量更新一下
            int totalStoreyNumber = storeyMapper.storeyQueryByInvitationId(invitationId).size();
            int totalCommentNumber = commentMapper.commentQueryByInvitationId(invitationId).size();
            invitationMapper.updateNumById("comment_number", totalStoreyNumber+totalCommentNumber, invitationId);
            //要将storey的comment数量更新一下
            int storeyCommentNumber = commentMapper.commentQueryByStoreyId(storeyId).size();
            storeyMapper.updateNumById("comment_number",storeyCommentNumber,storeyId);
            return "success";
        } catch (NullPointerException ne) {
            return "needLogin";//用户要登录
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
    /**
     * @author yuruiqiao
     * @date 2020/2/3
     * @description 用户support的方法
     */
    @RequestMapping(path = "/support")
    public String support(HttpSession session,@RequestParam("targetId") int targetId,@RequestParam("invitationId") int invitationId,
                          @RequestParam("targetType") String targetType){
        int flag = -1;
        try{
            int userId = ((User) session.getAttribute("user")).getUserId();
            Support mySupport = supportMapper.QueryMyselfSupport(targetId,targetType,userId);
            if(mySupport==null){
                Support support = new Support();
                support.setUserId(userId);
                support.setTargetId(targetId);
                support.setTargetType(targetType);
                support.setIsSupported(true);
                support.setInvitationId(invitationId);
                supportMapper.insert(support);
                flag = 1;
            }else{
                //如果有记录,查看当前用户对目标的支持状态
                boolean myselfIsSupport = mySupport.getIsSupported();
                if (myselfIsSupport) {
                    int i = supportMapper.updateSupportStatusByUserIdAndTargetId(targetId,targetType,false,userId);
                    if(i==1) {flag = 0;}

                } else {
                    int i = supportMapper.updateSupportStatusByUserIdAndTargetId(targetId,targetType,true,userId);
                    if(i==1){flag = 1;}
                }
            }
            if (flag == 1||flag == 0) {
                //暂时只能增加storey的点赞数目,有待完善
                switch (targetType) {
                    case "storey": {
                        int totalSupportNumber = supportMapper.supportQueryByTargetId(targetId, targetType).size();
                        storeyMapper.updateNumById("support_number", totalSupportNumber, targetId);
                        break;
                    }
                    case "comment": {
                        int totalSupportNumber = supportMapper.supportQueryByTargetId(targetId, targetType).size();
                        commentMapper.updateSupportNumberById(totalSupportNumber, targetId);
                        break;
                    }
                    default:
                        return "illegal";
                }
                if(flag == 1){
                    return "1";//1表示点赞
                }
                return "0";//0表示取消
            } else {
                return "error";
            }
        }catch (NullPointerException ne){
            return "needLogin";//用户要登录
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
    }
    /**
     * @author yuruiqiao
     * @date 2020/2/3
     * @description 刷新support的数量
     */
    @RequestMapping(path = "/update/support")
    public int updateSupport(@RequestParam("targetId") int targetId,@RequestParam("targetType") String targetType){
        if(targetType.equals("storey")){
            return storeyMapper.selectByPrimaryKey(targetId).getSupportNumber();
        }else if(targetType.equals("comment")){
            return commentMapper.selectByPrimaryKey(targetId).getSupportNumber();
        }
        return -1;
    }
}
